package leetcode.biweekly.week102;

import java.util.LinkedList;
import java.util.Queue;

import leetcode.helper.tree.TreeNode;

//Solution3Test
public class Solution3 {

	public TreeNode replaceValueInTree(TreeNode root) {
		Queue<TreeNode> queue = new LinkedList<>();
		queue.add(root);
		while (!queue.isEmpty()) {
			int size = queue.size();
			long sum = 0;
			while (size != 0) {
				TreeNode cur = queue.poll();
				if (cur.left != null) {
					sum += cur.left.val;
				}
				if (cur.right != null) {
					sum += cur.right.val;
				}
				queue.add(cur);
				size--;
			}
			size = queue.size();
			while (size != 0) {
				TreeNode cur = queue.poll();
				int t = 0;
				if (cur.left != null) {
					t += cur.left.val;
					queue.add(cur.left);
				}
				if (cur.right != null) {
					t += cur.right.val;
					queue.add(cur.right);
				}
				if (cur.left != null) {
					cur.left.val = (int) (sum - t);
				}
				if (cur.right != null) {
					cur.right.val = (int) (sum - t);
				}
				size--;

			}
		}

		root.val = 0;
		return root;
	}
}
